a = [1,2,3,4]

for x in reversed(a): # 倒序并生成迭代器
    print(x)

f = open('/etc/passwd') #反向迭代仅仅当对象的大小可预先确定或者对象实现了 __reversed__() 的特殊方法时才能生效。
for line in reversed(list(f)):
    print(line, end='')

# 自定义类上实现 __reversed__() 方法来实现反向迭代
class CountDown:
    def __init__(self,start):
        self.start = start

    def __iter__(self):
        n = self.start
        while n > 0 :
            yield n
            n -= 1

    def __reversed__(self):
        n = 1
        while n <= self.start:
            yield n
            n += 1

for rr in reversed(CountDown(30)):
    print(rr)
for rr in CountDown(30):
    print(rr)